<script setup>
import productService from '@/api/modules/product.js'
import ColorScheme from '@/components/ColorScheme/ColorScheme.vue'
import LanguageSelect from '@/components/LanguageSelect/LanguageSelect.vue'
import SvgIcon from '@/components/SvgIcon/SvgIcon.vue'
import useAppStore from '@/store/modules/app.js'
import { useUserStore } from '@/store/modules/user.js'
import { getToken } from '@/utils/auth.js'
import { getLocalImageUrl, setImgUrl } from '@/utils/index.js'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'

const { t } = useI18n()
const title = import.meta.env.VITE_APP_TITLE
const router = useRouter()
const token = getToken()
const userStore = useUserStore()
const appStore = useAppStore()
const userMenuOptions = reactive([
  {
    label: t('user.myOrders'),
    icon: renderIcon('lets-icons:order'),
    key: 'order',
  },
  {
    label: t('user.userInfo'),
    icon: renderIcon('fe:user'),
    key: 'info',
  },
  {
    type: 'divider',
    key: 'd1',
  },
  {
    label: t('LogOut'),
    icon: renderIcon('line-md:logout'),
    key: 'logout',
  },
])
const searchText = ref('')
const searchOptions = ref([])

function handleShowAuthForm(type) {
  userStore.toggleAuthFormModal(true, type)
}

function renderIcon(icon) {
  return () => {
    return h(SvgIcon, {
      name: icon,
      style: 'font-size: 19px',
    })
  }
}

function handleSelect(type) {
  if (type === 'logout') {
    // userStore.logout()
    window.$dialog.warning({
      title: t('SystemPrompts'),
      content: t('message.confirmLogout'),
      positiveText: t('button.confirm'),
      negativeText: t('button.cancel'),
      onPositiveClick: () => {
        userStore.logout()
        router.push('/')
        appStore.reloadPage()
      },
    })
  }
  else {
    console.log(type)
    router.push({
      path: `/user/${type}`,
    })
  }
}

function handleSearch(value) {
  const params = {
    pageNum: 1,
    pageSize: 5,
    productName: value,
    dele: 0,
  }
  productService.list(params).then((res) => {
    searchOptions.value = res?.rows.map((item) => {
      return {
        value: item.productName,
        label: item.productName,
      }
    })
  })
}

function handleSearchSubmit() {
  router.push({
    path: '/home',
    query: {
      keyword: searchText.value,
    },
  })
}
</script>

<template>
  <nav class="bg-white dark:bg-gray-800 shadow-md sticky top-0 z-10">
    <div class="container mx-auto px-4 sm:px-6 lg:px-8">
      <div class="flex items-center justify-between h-20">
        <router-link to="/" class="flex-shrink-0 flex items-center">
          <img alt="Logo" loading="lazy" width="32" height="32" decoding="async" data-nimg="1" src="@/assets/img/logo.png" style="">
          <span class="font-semibold text-xl tracking-tight ml-2">{{ title }}</span>
        </router-link>
        <div class="flex-1 max-w-xl mx-4">
          <n-input-group>
            <n-auto-complete
              v-model:value="searchText" :options="searchOptions"
              @update:value="handleSearch"
            >
              <template #default="{ handleInput, handleBlur, handleFocus, value: slotValue }">
                <n-input
                  size="large"
                  :value="slotValue"
                  clearable
                  @input="handleInput"
                  @focus="handleFocus"
                  @blur="handleBlur"
                />
              </template>
            </n-auto-complete>
            <n-button type="primary" size="large" @click="handleSearchSubmit">
              {{ t('header.search-btn') }}
            </n-button>
          </n-input-group>
        </div>
        <div class="flex items-center space-x-4">
          <router-link to="/cart" class="inline-flex items-center justify-center gap-2 wring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 hover:bg-accent hover:text-accent-foreground h-10 w-10">
            <SvgIcon name="akar-icons:cart" class="text-xl cursor-pointer" />
          </router-link>
          <div class="inline-flex items-center justify-center gap-2 wring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 hover:bg-accent hover:text-accent-foreground h-10 w-10">
            <ColorScheme />
          </div>
          <div class="inline-flex items-center justify-center gap-2 wring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 hover:bg-accent hover:text-accent-foreground h-10 w-10">
            <LanguageSelect />
          </div>
          <div class="inline-flex items-center justify-center gap-2 wring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 hover:bg-accent hover:text-accent-foreground h-10 px-4 py-2 ml-3">
            <template v-if="token">
              <n-avatar v-if="userStore.userInfo.avatar !== '' " :src="setImgUrl(userStore.userInfo.avatar)" :size="36" round />
              <n-avatar v-else :size="35" :src="getLocalImageUrl('avatar.png')" round />
              <n-dropdown
                :options="userMenuOptions"
                trigger="hover"
                placement="bottom-end"
                @select="handleSelect"
              >
                <span class="hidden sm:inline-block text-base">{{ userStore.userInfo.userName }}</span>
              </n-dropdown>
            </template>
            <template v-else>
              <SvgIcon name="tabler:user" class="text-xl" />
              <span class="hidden sm:inline-block">
                <span class="cursor-pointer" @click="handleShowAuthForm('login')">{{ t('header.login') }}</span> / <span class="cursor-pointer" @click="handleShowAuthForm('register')">{{ t('header.register') }}</span>
              </span>
            </template>
          </div>
        </div>
      </div>
    </div>
  </nav>
</template>

<style lang="scss" scoped>

</style>
